Skip to content

[25.03.09 / TASK-136] Feature - post repo order test, 레포 계층 테스팅과 CI 파이프라인 #20

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Mar 13, 2025

Conversation

Nuung
Copy link
Member

@Nuung Nuung commented Mar 9, 2025

  • 세부 통계 값 API 정렬 이슈 핸들링
  • 이를 위한 post 레포 계층 독립 테스트 코드 작성
  • 그리고 git action CI 파이프라인 구축

Summary by CodeRabbit

  • New Features
    • 게시물 데이터가 날짜 순으로 정렬되어, 보다 일관되고 명확한 정보 표시가 가능합니다.
    • 새로운 테스트 스위트가 PostRepository 클래스의 기능을 검증합니다.
  • Bug Fixes
    • 기본적인 덧셈 로직을 검증하는 테스트 케이스가 제거되었습니다.
  • Chores
    • 다양한 환경에서 자동 빌드 및 테스트가 실행되는 CI 워크플로우를 도입하여, 제품의 안정성과 품질을 강화했습니다.
  • Documentation
    • README 파일에 Node.js 버전 20 이상이 필요하다는 내용을 추가했습니다.
    • 백엔드 API 서버의 설명이 보다 구체적으로 업데이트되었습니다.

@Nuung Nuung added documentation Improvements or additions to documentation enhancement New feature or request labels Mar 9, 2025
@Nuung Nuung self-assigned this Mar 9, 2025
Copy link

Copy link
Contributor

coderabbitai bot commented Mar 9, 2025

Walkthrough

이번 변경사항에서는 GitHub Actions를 활용한 CI 워크플로우(test-ci.yaml)가 새롭게 추가되어, main 브랜치에 대한 푸시, PR, 수동 디스패치 시 여러 Node.js 버전(20~23)에서 빌드, 테스트, 린트 및 빌드 작업을 수행하도록 구성되었습니다. 또한, 기본 덧셈 테스트 케이스가 제거되고, PostRepository 관련 테스트 스위트가 추가되어 다양한 메서드의 기능과 오류 처리를 검증하며, findPostByPostId 메서드에 날짜순 정렬(ORDER BY pds.date ASC) 절이 추가되었습니다.

Changes

파일 변경 내용
.github/workflows/test-ci.yaml 새 CI 워크플로우 추가: Node.js 매트릭스 활용, pnpm 사용, 린트/테스트/빌드 단계를 포함
src/test/sum.test.ts 단순 덧셈 테스트 케이스 (1 + 2 = 3) 제거
src/repositories/test/post.repository.test.ts PostRepository 관련 테스트 스위트 추가 및 다양한 메서드 기능 검증
src/repositories/post.repository.ts findPostByPostId 메서드에 ORDER BY 절 추가
README.md 백엔드 API 서버 설명 수정 및 Node.js 버전 요구 사항 추가

Suggested labels

bug

Suggested reviewers

  • BDlhj
  • six-standard

Poem

나는 작은 토끼, 코드를 뛰어넘어
CI의 길 따라 깡총깡총 달리네 🐇
Node.js의 세계에서 춤추는 발자국,
테스트와 빌드가 어우러진 신나는 축제!
깔끔한 쿼리 정렬로 하루를 채우며
오늘도 코드 숲을 한가득 누비네!


🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
.github/workflows/test-ci.yaml (1)

1-41: GitHub Actions CI 설정이 잘 구성되었습니다!

CI 파이프라인이 적절하게 구성되어 있습니다. 여러 Node.js 버전(18~23)에서 테스트를 실행하여 다양한 환경에서의 호환성을 확인하는 전략이 좋습니다.

몇 가지 개선 제안:

  1. 의존성 캐싱을 더 효율적으로 활용할 수 있습니다 (현재 캐시 설정은 되어있지만 최적화 가능).
  2. 각 실행 단계에 더 명확한 이름을 추가하면 GitHub Actions UI에서 가시성이 향상됩니다.
  3. 테스트 결과 및 커버리지 리포트를 저장하는 단계를 추가하는 것을 고려해 보세요.
 name: Test CI

 on:
   workflow_dispatch:
   push:
     branches: ['main']
   pull_request:
     branches:
       - main

 jobs:
   build-and-test:
     runs-on: ubuntu-latest
     strategy:
       matrix:
         node-version: [18, 19, 20, 21, 22, 23]
+      fail-fast: false
     steps:
       - name: Checkout repository
         uses: actions/checkout@v4

       - name: Set up Node.js ${{ matrix.node-version }}
         uses: actions/setup-node@v4
         with:
           node-version: ${{ matrix.node-version }}
           cache: 'pnpm'

       - name: Install pnpm
         run: npm install -g pnpm

       - name: Install dependencies
         run: pnpm install --frozen-lockfile
+        timeout-minutes: 5

       - name: Run lint
+        id: lint
         run: pnpm run lint

       - name: Run tests
+        id: test
         run: pnpm run test
+        timeout-minutes: 10

       - name: Run build
+        id: build
         run: pnpm run build
+        timeout-minutes: 5
src/repositories/__test__/post.repository.test.ts (1)

1-146: PostRepository 테스트 케이스가 잘 작성되었습니다!

테스트 스위트가 PostRepository 클래스의 주요 메서드들을 효과적으로 테스트하고 있습니다. PostgreSQL Pool을 모킹하여 실제 데이터베이스 연결 없이 테스트를 수행하는 방식이 적절합니다.

개선 제안:

  1. Edge case 테스트 추가: 빈 결과, null 값, 오류 상황 등의 엣지 케이스에 대한 테스트를 더 추가하면 좋겠습니다.
  2. findPostByPostId 메서드의 날짜 필터링(start, end 파라미터) 기능에 대한 더 구체적인 테스트가 필요합니다.
  3. 각 테스트 케이스가 단순히 결과값만 확인하는 것이 아니라, 실제 SQL 쿼리가 적절하게 구성되는지 확인하는 테스트를 추가하면 좋겠습니다.

특히 아래와 같이 findPostByPostId 테스트를 확장하면 더 견고해질 것입니다:

// findPostByPostId에 대한 추가 테스트 예시
it('날짜 필터링이 있는 경우 올바른 SQL 쿼리를 생성해야 한다', async () => {
  mockPool.query.mockImplementation((query, params) => {
    // 쿼리 및 파라미터 검증
    expect(params.length).toBe(3);
    expect(params[0]).toBe(1); // postId
    expect(params[1]).toBe('2025-03-01'); // start
    expect(params[2]).toBe('2025-03-08'); // end
    expect(query).toContain('ORDER BY pds.date ASC');
    expect(query).toContain('WHERE pds.post_id = $1');
    expect(query).toContain('AND (pds.date AT TIME ZONE');

    return Promise.resolve({
      rows: [],
      rowCount: 0,
      command: '',
      oid: 0,
      fields: [],
    } as QueryResult);
  });

  await repo.findPostByPostId(1, '2025-03-01', '2025-03-08');
  expect(mockPool.query).toHaveBeenCalled();
});

it('결과가 없는 경우 빈 배열을 반환해야 한다', async () => {
  mockPool.query.mockResolvedValue({
    rows: [],
    rowCount: 0,
    command: '',
    oid: 0,
    fields: [],
  } as QueryResult);

  const result = await repo.findPostByPostId(999);
  expect(result).toEqual([]);
});
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 60c8f66 and f41c176.

📒 Files selected for processing (4)
  • .github/workflows/test-ci.yaml (1 hunks)
  • src/__test__/sum.test.ts (0 hunks)
  • src/repositories/__test__/post.repository.test.ts (1 hunks)
  • src/repositories/post.repository.ts (1 hunks)
💤 Files with no reviewable changes (1)
  • src/test/sum.test.ts
🔇 Additional comments (1)
src/repositories/post.repository.ts (1)

172-172: 정렬 기능 추가로 데이터 일관성 향상!

findPostByPostId 메서드에 ORDER BY pds.date ASC 구문을 추가함으로써 날짜 기준으로 일관된 정렬이 이루어지게 되었습니다. 이 변경은 findPostByPostUUID 메서드(203번 줄)에서 이미 사용 중인 정렬 방식과 일치하게 만들어 메서드 간 일관성을 유지하고, 통계 데이터를 시간 순서대로 조회할 수 있게 해줍니다.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
.github/workflows/test-ci.yaml (1)

50-60: 종속성 설치 및 후속 스텝 검토

  • 종속성 설치(pnpm install --frozen-lockfile), 린트(pnpm run lint), 테스트(pnpm run test), 빌드(pnpm run build) 단계가 순차적으로 잘 설정되어 있습니다.

또한, YAMLlint 도구에서 지적한 바와 같이 파일 마지막 줄(line 60) 뒤에 개행문자가 없습니다. 파일 끝에 개행 추가 부탁드립니다.

🧰 Tools
🪛 YAMLlint (1.35.1)

[error] 60-60: no new line character at the end of file

(new-line-at-end-of-file)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a0acc5d and ff444bc.

📒 Files selected for processing (1)
  • .github/workflows/test-ci.yaml (1 hunks)
🧰 Additional context used
🪛 actionlint (1.7.4)
.github/workflows/test-ci.yaml

43-43: the runner of "actions/cache@v3" action is too old to run on GitHub Actions. update the action's version to fix this issue

(action)

🪛 YAMLlint (1.35.1)
.github/workflows/test-ci.yaml

[error] 60-60: no new line character at the end of file

(new-line-at-end-of-file)

🔇 Additional comments (6)
.github/workflows/test-ci.yaml (6)

1-2: CI 워크플로우 파일 생성 및 이름 지정 검토

새로운 GitHub Actions 워크플로우 파일이 올바르게 생성되었으며, 이름이 "Test CI"로 지정되어 있습니다.


3-9: 이벤트 트리거 설정 확인

workflow_dispatch, pushpull_request 이벤트가 main 브랜치에 대해 올바르게 설정되어 있어, 다양한 상황에서 CI가 실행될 수 있습니다.


10-17: JOB 전략 및 매트릭스 설정 검토

build-and-test Job이 Ubuntu 최신 환경에서 실행되며, Node.js 버전 매트릭스([20, 21, 22, 23])와 fail-fast: false 옵션을 통해 여러 버전에서 병렬 테스트가 가능하도록 구성됨이 적절해 보입니다.


18-29: 빌드 스텝 및 Corepack 설정 검토

  • Repository 체크아웃, Node.js 설정 (actions/setup-node@v4), 그리고 Corepack 활성화(corepack enable) 단계가 문제없이 구성되어 있습니다.

30-35: pnpm 설치 및 설정 확인

pnpm/action-setup@v2를 사용하여 pnpm을 설치하고 있으며, 버전 9와 run_install: false 설정이 올바르게 지정되어 있습니다.


36-41: pnpm 스토어 경로 설정 검토

pnpm 스토어 경로를 $GITHUB_OUTPUT에 저장하는 로직이 명확하며, 이후 캐시 설정에 활용할 수 있도록 잘 구성되었습니다.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ff444bc and a6612de.

📒 Files selected for processing (1)
  • .github/workflows/test-ci.yaml (1 hunks)
🧰 Additional context used
🪛 YAMLlint (1.35.1)
.github/workflows/test-ci.yaml

[error] 60-60: no new line character at the end of file

(new-line-at-end-of-file)

🔇 Additional comments (12)
.github/workflows/test-ci.yaml (12)

1-2: 워크플로우 이름 확인
워크플로우 제목인 "Test CI"가 목적에 맞게 잘 정의되어 있습니다.


3-9: 트리거(trigger) 설정 검토
workflow_dispatch, push, pull_request 이벤트와 main 브랜치 대상의 설정이 적절하게 구성되어 있어 다양한 상황에서 CI가 실행될 것으로 보입니다.


10-17: Job 구성 및 매트릭스 전략 검토
여러 Node.js 버전을 대상으로 한 매트릭스 전략과 fail-fast: false 옵션이 올바르게 설정되어 있어, 특정 버전의 실패가 전체 파이프라인에 영향을 주지 않도록 처리되었습니다.


18-21: 체크아웃 단계 확인
저장소 체크아웃에 actions/checkout@v4를 사용한 점은 최신 권장 버전이며, 올바르게 작동할 것으로 예상됩니다.


22-26: Node.js 설정 단계 검토
actions/setup-node@v4를 사용하여 매트릭스에서 전달된 Node.js 버전을 설정하는 부분이 정확하게 구현되어 있습니다.


27-29: Corepack 활성화 검토
Corepack을 활성화하는 run: corepack enable 명령이 포함되어 있어, 이후 pnpm 사용에 문제없이 동작할 것으로 보입니다.


30-35: pnpm 설정 단계 검토
pnpm/action-setup@v2를 사용하여 버전 9의 pnpm을 설치하고, 이후 별도의 설치 과정을 실행하지 않도록 run_install: false 옵션을 설정한 점이 좋습니다.


36-41: pnpm 스토어 디렉토리 획득 단계 검토
pnpm store 경로를 획득하여 $GITHUB_OUTPUT에 저장하는 로직이 명확하며, 이후 캐시 설정에 활용할 수 있도록 잘 처리되었습니다.


42-49: pnpm 캐시 설정 검토
actions/cache@v4를 사용하여 pnpm 캐시를 설정하고, 고유한 키와 restore-keys를 지정한 점이 캐시 활용에 적절합니다.


50-52: 의존성 설치 단계 확인
pnpm install --frozen-lockfile 명령어를 사용하여 락파일에 기반한 설치를 수행하도록 설정한 점이 좋습니다.


53-55: Lint 실행 단계 확인
pnpm run lint 명령이 포함되어 있어, 코드 품질 관리에 도움이 될 것으로 보입니다.


56-58: 테스트 실행 단계 확인
pnpm run test 명령을 통해 테스트가 실행되며, 다양한 Node.js 버전에서의 테스트가 기대됩니다.

Copy link

@Jihyun3478 Jihyun3478 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

좋았던 점

  • test-ci 파일 및 구체적인 워크플로우를 다시 한 번 꼼꼼히 살펴볼 수 있어서 좋았습니다!
  • 테스트코드가 단위테스트로 구현되어있어, 각 테스트별 의도하는 바가 확실히 전달되었던 것 같습니다:)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

테스트에 대한 CI는 이번에 처음 접하게 되었는데, 전체적으로 잘 구성된 워크플로우 같아 배우고갑니다!
특히, matrix.node-version에 대해서 찾아본 결과 여러 Node.js 버전을 테스트하도록 활용하신 부분이 인상적이었습니다!

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

junit, pytest, 그리고 jest까지 사용되는 언어만 다를뿐 mocking, equal, greaterThan, throw까지 동작하는 방식은 비슷하다는 점이 인상깊은 것 같습니다!

기능적인 부분에 대한 질문은 아니지만, 테스트코드를 구현할 때 가장 중요하게 생각하시는 부분이 무엇인지 현우님만의 관점이 궁금합니다!

Copy link
Member

@six-standard six-standard left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

리뷰중에 테스트 CI는 처음 보는 것 같다는 말이 있던데, 저도 처음 봐서 조금 신기하네요.
아무튼 코드 잘 읽었습니다!

좋았던 점

  • 드디어 서버 측에서 날짜 정렬 오류 핸들링이 된 듯 합니다 (이제 리팩토링으로 클라이언트측 날짜 정렬 코드만 제거하면 되겠네요)
  • Node 버전 명시덕분에 초기 세팅시 훨씬 유용할 듯 합니다 (초기 버전이 17인 분듣로 많으니까요..)

@Nuung Nuung merged commit bc1a377 into main Mar 13, 2025
5 checks passed
@Nuung Nuung deleted the feature/post-repo-order-test branch March 13, 2025 15:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
documentation Improvements or additions to documentation enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants